﻿using Microsoft.AspNet.SignalR.Hosting;
using Microsoft.EntityFrameworkCore;
using SmartWMS.Common.Extensions;
using SmartWMS.Common.ResponseOutput;
using SmartWMS.Domain.BasicsDatum;
using SmartWMS.EntityFramework;
using SmartWMS.Server.BasicsDatumServer.CustomerManagementService.Dto;
using SmartWMS.Server.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SmartWMS.Server.BasicsDatumServer.CustomerManagementService
{
	/// <summary>
	/// 客户管理
	/// </summary>
	public class CustomerManagementService : ICustomerManagementService
	{
		private readonly SmartWMSContext Db;
		private readonly IRepository<Custom> _customResponse;
		private readonly IRepository<CustomContact> _customContactResponse;

		public CustomerManagementService(IRepository<Custom> customResponse, IRepository<CustomContact> customContactResponse, SmartWMSContext db)
		{
			_customResponse = customResponse;
			_customContactResponse = customContactResponse;
			Db = db;
		}

		/// <summary>
		/// 显示客户管理信息
		/// </summary>
		/// <param name="dto">要查询的客户对象 + 分页对象</param>
		/// <returns></returns>
		public async Task<(int pageCount, int totalCount, Response<List<CustomDto>> data)> GetCustomerManagemenDtoAsync(SearchCustomDto dto)
		{
			try
			{
				var customList = await _customResponse.GetAllListAsync();
				var customContactList = await _customContactResponse.GetAllListAsync();

				var list = (from custom in customList
							join customContact in customContactList on custom.CustomrCode equals customContact.CustomrCode
							select new CustomDto
							{
								Id = custom.Id,
								CustomrCode = custom.CustomrCode,
								CustomName = custom.CustomName,
								Fax = custom.Fax,
								Phone = custom.Phone,
								Email = custom.Email,
								Comment = custom.Comment,
								Contacts = customContact.Contacts,
								Address = customContact.Address,
								CustomContactPhone = customContact.Phone,
								CreateTime = customContact.CreateTime
							}).Distinct().ToList();

				if (!string.IsNullOrEmpty(dto.CustomrCode))
				{
					list = list.Where(x => x.CustomrCode.Contains(dto.CustomrCode)).ToList();
				}

				if (!string.IsNullOrEmpty(dto.CustomName))
				{
					list = list.Where(x => x.CustomName.Contains(dto.CustomName)).ToList();
				}

				if (!string.IsNullOrEmpty(dto.Phone))
				{
					list = list.Where(x => x.Phone.Contains(dto.Phone)).ToList();
				}

				//计算总页数
				int totalCount = list.Count();
				int pageCount = (int)Math.Ceiling(totalCount * 1.0 / dto.pageSize);
				list = list.Skip((dto.pageIndex - 1) * dto.pageSize).Take(dto.pageSize).ToList();

				var result = list.MapToList<CustomDto>();
				return (pageCount, totalCount, Response<List<CustomDto>>.Ok(result));
			}
			catch (Exception)
			{
				throw;
			}
		}

		/// <summary>
		/// 删除客户管理
		/// </summary>
		/// <param name="info">要删除的客户实体</param>
		/// <returns></returns>
		public async Task<Response<bool>> DelCustomerManagement(CustomDto info)
		{
			try
			{
				var result = info.MapTo<Custom>();
				var data = await _customResponse.DeleteByIdAsync(result);
				return data > 0 ? Response<bool>.Ok(true) : Response<bool>.Fail(false);
			}
			catch (Exception)
			{
				throw;
			}
		}

		/// <summary>
		/// 批量删除客户管理
		/// </summary>
		/// <param name="dto"></param>
		/// <returns></returns>
		public Task<Response<bool>> BatchDelCustomerManagement(CustomDto dto)
		{
			try
			{
				var sid = dto.DelId.Split(',');
				var list = new List<Custom>();
				foreach (var item in sid)
				{
					var warehouseList = _customResponse.GetListQuery().Where(x => x.Id == int.Parse(item)).ToList();
					list.AddRange(warehouseList);
				}

				var result = _customResponse.DeleteAsync(list);
				return result.Result > 0 ? Task.FromResult(Response<bool>.Ok(result.Result > 0)) : Task.FromResult(Response<bool>.Fail(result.Result > 0));
			}
			catch (Exception)
			{
				throw;
			}
		}

		/// <summary>
		/// 添加客户管理（客户联系人）
		/// </summary>
		/// <param name="dto"></param>
		/// <returns></returns>
		public async Task<Response<bool>> AddCustomDtoAsync(CustomDto info)
		{
			try
			{
				//开启事务
				using (var tran = Db.Database.BeginTransaction())
				{
					try
					{
						var list = await _customResponse.GetAllListAsync();
						//判断客户名称是否重复
						list = list.Where(x => x.CustomName == info.CustomName).ToList();
						if (list.Count > 0)
						{
							return Response<bool>.Fail("客户名称已存在，请重新输入！");
						}

						int CustomContactList = await _customResponse.InsertAsync(info.MapTo<Custom>());
						if (CustomContactList > 0)
						{
							var result = new List<CustomContact>();
							foreach (var item in info.CustomContactDtosList)
							{
								result.Add(new CustomContact
								{
									Address = item.Address,
									Contacts = item.Contacts,
									CreateTime = DateTime.Now,
									CustomrCode = info.CustomrCode,
									Phone = item.Phone
								});
							}
							int i = await _customContactResponse.InsertAsync(result);
						}

						//提交事务
						tran.Commit();

						return CustomContactList > 0 ? Response<bool>.Ok(true) : Response<bool>.Fail(false);
					}
					catch (Exception)
					{
						//事务回滚
						tran.Rollback();
						throw;
					}
				}
			}
			catch (Exception)
			{
				throw;
			}
		}

		/// <summary>
		/// 反填客户联系人信息
		/// </summary>
		/// <param name="info">要反填的客户联系人信息实体</param>
		/// <returns></returns>
		public async Task<Response<List<CustomContactDto>>> FillCustomContactDtoAsync(CustomContactDto info)
		{
			try
			{
				var result = await _customContactResponse.GetListQuery().Where(x => x.CustomrCode == info.CustomrCode).ToListAsync();

				var list = result.MapToList<CustomContactDto>();

				return Response<List<CustomContactDto>>.Ok(list);
			}
			catch (Exception)
			{
				throw;
			}
		}

		/// <summary>
		/// 反填客户信息
		/// </summary>
		/// <param name="info">要反填的客户信息</param>
		/// <returns></returns>
		public async Task<Response<CustomInputDto>> GetCustomDtoAsync(CustomInputDto info)
		{
			try
			{
				var result = _customResponse.GetListQuery().FirstOrDefault(x => x.Id == info.Id);

				var list = result.MapTo<CustomInputDto>();

				//list.CustomContactDtosList = (from a in Db.Custom
				//							  join b in Db.CustomContact
				//							  on a.CustomrCode equals b.CustomrCode
				//							  where b.CustomrCode != info.CustomrCode
				//							  select new CustomContactDto
				//							  {
				//								  CustomrCode = a.CustomrCode,
				//								  Address = b.Address,
				//								  Contacts = b.Contacts,
				//								  CreateTime = b.CreateTime,
				//								  Phone = b.Phone,
				//								  Editable = b.Editable
				//							  }).ToList();

				return list != null ? Response<CustomInputDto>.Ok(list) : Response<CustomInputDto>.Fail("失败");
			}
			catch (Exception)
			{
				throw;
			}
		}

		/// <summary>
		/// 修改客户信息
		/// </summary>
		/// <param name="info">要修改的客户信息</param>
		/// <returns></returns>
		public async Task<Response<bool>> UpdCustomDtoAsync(CustomDto info)
		{
			try
			{
				int i = 0;

				int AddCustom = await _customResponse.UpdateAsync(info.MapTo<Custom>());

				if (AddCustom > 0)
				{
					var delete = _customContactResponse.GetAllListAsync().Result.Where(x => x.CustomrCode == info.CustomrCode).ToList();

					await _customContactResponse.DeleteAsync(delete);

					var result = new List<CustomContact>();
					foreach (var item in info.CustomContactDtosList)
					{
						result.Add(new CustomContact
						{
							Address = item.Address,
							Contacts = item.Contacts,
							CreateTime = DateTime.Now,
							CustomrCode = info.CustomrCode,
							Phone = item.Phone
						});
					}
					i = await _customContactResponse.InsertAsync(result);
				}

				return i > 0 ? Response<bool>.Ok(true) : Response<bool>.Fail(false);
			}
			catch (Exception)
			{
				throw;
			}
		}
	}
}
